package com.hnjfzn.auth.factory;

import com.hnjfzn.auth.service.SysPasswordService;
import com.hnjfzn.auth.service.SysRecordLogService;
import com.hnjfzn.common.core.constant.Constants;
import com.hnjfzn.common.core.constant.UserConstants;
import com.hnjfzn.common.core.exception.ServiceException;
import com.hnjfzn.common.core.utils.StringUtils;
import com.hnjfzn.common.redis.service.RedisService;
import com.hnjfzn.system.api.RemoteUserService;
import com.hnjfzn.system.api.domain.SysUser;

public class UsernameLogin extends AbsSysLogin {
    /**
     * 构造
     *
     * @param remoteUserService 远程用户服务
     * @param passwordService   密码服务
     * @param recordLogService  日志服务
     * @param redisService      缓存服务
     */
    public UsernameLogin(RemoteUserService remoteUserService, SysPasswordService passwordService, SysRecordLogService recordLogService, RedisService redisService) {
        super(remoteUserService, passwordService, recordLogService, redisService);
    }

    @Override
    protected void validAfter(String... args) {
        String username = args[0], password = args[1];
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
    }

    @Override
    protected void validBefore(SysUser user, String... args) {
        passwordService.validate(user, args[1]);
    }
}
